{extend name="base" /}

{block name="title"}用户管理{/block}

{block name="body"}
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">账&emsp;号</label>
                        <div class="layui-input-inline">
                            <input name="username" class="layui-input" autocomplete="off" placeholder="输入账号关键词"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">昵&emsp;称</label>
                        <div class="layui-input-inline">
                            <input name="nickname" class="layui-input" autocomplete="off" placeholder="输入昵称关键词"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">创建时间</label>
                        <div class="layui-input-inline">
                            <input name="createDateSel" class="layui-input icon-date" placeholder="选择日期范围" autocomplete="off"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">状&emsp;态</label>
                        <div class="layui-input-inline">
                            <select name="status">
                                <option value="">--- 全部 ---</option>
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn" lay-filter="userTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="userTbBar">
    <a class="layui-btn layui-btn-xs {{(d.id != {$admin_id} && d.is_admin == 1)?'layui-btn-disabled':''}}" {{(d.id != {$admin_id} && d.is_admin == 1)?'':'lay-event="edit"'}}>修改</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger {{(d.id == {$admin_id} || d.is_admin == 1)?'layui-btn-disabled':''}}" {{(d.id == {$admin_id} || d.is_admin == 1)?'':'lay-event="del"'}}>删除</a>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbState">
    <input type="checkbox" lay-filter="userTbStateCk" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" {{d.status==1?'checked':''}} style="display: none;"/>
    <p style="display: none;">{{d.status==1?'启用':'禁用'}}</p>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="userEditDialog">
    <form id="userEditForm" lay-filter="userEditForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">登录账号</label>
            <div class="layui-input-block">
                <input name="username" class="layui-input" autocomplete="off" placeholder="请输入登录账号" minlength="2" maxlength="20" lay-verType="tips" lay-verify="required|h5" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">账号昵称</label>
            <div class="layui-input-block">
                <input name="nickname" class="layui-input" autocomplete="off" placeholder="请输入账号昵称" minlength="2" maxlength="20" lay-verType="tips" lay-verify="required|h5" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">新 密 码</label>
            <div class="layui-input-block">
                <input type="password" name="newpassword" placeholder="请输入新密码" class="layui-input" autocomplete="off" lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">确认密码</label>
            <div class="layui-input-block">
                <input type="password" name="repassword" placeholder="请再次输入新密码" class="layui-input" autocomplete="off" lay-verType="tips" lay-verify="required|equalTo" lay-equalTo="input[name=newpassword]" lay-equalToText="两次输入密码不一致" required/>
            </div>
        </div>
        <div class="layui-form-item" id="roleName">
            <label class="layui-form-label layui-form-required">所属角色</label>
            <div class="layui-input-block">
                <div id="userEditRoleSel"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="userEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" mx-event="closeDialog">取消</button>
        </div>
    </form>
</script>
{/block}

{block name="script"}
<script>
    layui.use(['layer', 'form', 'formX', 'table', 'admin', 'xmSelect', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;
        var laydate = layui.laydate;

        /* 渲染表格 */
        var insTb = table.render({
            elem: '#userTable',
            url: "{:url('mxadmin/admin/datalist')}",
            page: {limit: 15},
            limits: [15, 30, 45, 60, 75, 90, 100, 200, 500],
            toolbar: ['<p>',
                '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>批量删除</button>',
                '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加账号</button>&nbsp;',
                '</p>'].join(''),
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'},
                {field: 'id', title: '用户ID', align: 'center', sort: true, width: 90},
                {field: 'username', title: '账号', align: 'center', sort: true},
                {field: 'nickname', title: '昵称', align: 'center', sort: true},
                {
                    field: 'roleName', title: '所属角色', align: 'center', templet: function (d) {
                        if(d.is_admin == 1){
                            return '<span class="layui-badge layui-badge-red">超级管理员</span>';
                        }else{
                            return d.roles.map(function (item) {
                                return '<span class="layui-badge layui-badge-green">' + item.title + '</span>';
                            }).join('&nbsp;&nbsp;');
                        }
                    }
                },
                {field: 'last_login_time', title: '上次登录时间', align: 'center', sort: true},
                {field: 'login_time', title: '登录时间', align: 'center', sort: true},
                {field: 'create_time', title: '创建时间', align: 'center', sort: true},
                {field: 'status', title: '状态', templet: '#userTbState', align: 'center', sort: true, width: 100},
                {title: '操作', toolbar: '#userTbBar', align: 'center', minWidth: 180}
            ]],
            parseData: function(res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            },
        });

        /* 渲染时间选择 */
        laydate.render({
            elem: 'input[name="createDateSel"]',
            type: 'date',
            range: true,
            trigger: 'click'
        });

        /* 表格搜索 */
        form.on('submit(userTbSearch)', function (data) {
            if (data.field.createDateSel) {
                var searchDate = data.field.createDateSel.split(' - ');
                data.field.startDate = searchDate[0];
                data.field.endDate = searchDate[1];
            } else {
                data.field.startDate = null;
                data.field.endDate = null;
            }
            data.field.createDateSel = undefined;
            insTb.reload({where: data.field, page: {curr: 1}, url:"{:url('mxadmin/admin/serach')}"});
            return false;
        });

        /* 表格操作列点击事件 */
        table.on('tool(userTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj,'您确定要删除“' + obj.data.username + '”的账号吗？');
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(userTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                var checkRows = table.checkStatus('userTable');
                if (checkRows.data.length === 0) {
                    layer.msg('请选择要删除的账号', {icon: 5, anim: 6});
                    return;
                }
                var ids = checkRows.data.map(function (d) {
                    return d.id;
                });
                doDel({ids: ids},'您确定要删除选中的这些账号吗？');
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                title: (mData ? '修改' : '添加') + '账号',
                shade: 0.5,
                //shadeClose: true,
                content: $('#userEditDialog').html(),
                success: function (layero, dIndex) {
                    // 回显表单数据
                    form.val('userEditForm', mData);
                    // 表单提交事件
                    form.on('submit(userEditSubmit)', function (data) {
                        data.field.role_id = insRoleSel.getValue('valueStr');
                        var loadIndex = layer.load(2);
                        $.post(mData ? "{:url('mxadmin/admin/edit')}" : "{:url('mxadmin/admin/add')}", data.field, function (res) {
                            layer.close(loadIndex);
                            if (res.code === 1) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload();  // 保存成功刷新表格
                            } else {
                                layer.msg(res.msg, {icon: 5, anim: 6});
                            }
                        }, 'json');
                        return false;
                    });
                    // 渲染多选下拉框
                    var insRoleSel = xmSelect.render({
                        el: '#userEditRoleSel',
                        name: 'userEditRoleSel',
                        layVerify: 'required',
                        layVerType: 'tips',
                        prop: {
                            name: 'title',
                            value: 'id',
                        },
                        data: {:json_encode($rolelist)}
                    });
                    // 回显选中角色
                    if (mData && mData.roles) {
                        insRoleSel.setValue(mData.roles.map(function (item) {
                            return item.group_id;
                        }));
                    }
                    // 编辑文本框状态
                    if (mData) {
                        $(layero).find('[name="username"]').attr('disabled','disabled').addClass("layui-bg-gray");
                        $(layero).find('[name="newpassword"]').removeAttr('lay-verType lay-verify required');
                        $(layero).find('[name="newpassword"]').attr('placeholder','若不修改密码，请留空');
                        $(layero).find('[name="repassword"]').attr('lay-verify','equalTo');
                        $(layero).find('[name="repassword"]').removeAttr('required');
                        if (mData.is_admin === 1) {$(layero).find('#roleName').remove();}
                    }
                    // 禁止弹窗出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }

        /* 删除 */
        function doDel(obj,txt) {
            layer.confirm(txt, {
                title: '删除账号',
                skin: 'layui-layer-admin',
                shade: 0.5,
                //shadeClose: true,
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                $.post("{:url('mxadmin/admin/del')}", {
                    id: obj.data ? obj.data.id : '',
                    ids: obj.ids ? obj.ids.join(',') : ''
                }, function (res) {
                    layer.close(loadIndex);
                    if (res.code === 1) {
                        layer.msg(res.msg, {icon: 1});
                        insTb.reload();
                    } else {
                        layer.msg(res.msg, {icon: 5, anim: 6});
                    }
                }, 'json');
            });
        }

        /* 修改用户状态 */
        form.on('switch(userTbStateCk)', function (obj) {
            var loadIndex = layer.load(2);
            $.post("{:url('mxadmin/admin/edit_state_same')}", {
                id: obj.elem.value,
                status: obj.elem.checked ? 1 : 0
            }, function (res) {
                layer.close(loadIndex);
                if (res.code === 1) {
                    layer.msg(res.msg);
                    insTb.reload();
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'json');
        });
    });
</script>
{/block}
